package com.wosiliujing.learning.config;

import com.wosiliujing.learning.component.Oauth2WebResponseExceptionTranslator;
import com.wosiliujing.learning.constant.SecurityConstants;
import com.wosiliujing.learning.entity.SecurityUser;
import com.wosiliujing.learning.properties.SecurityProperties;
import com.wosiliujing.learning.service.ClientDetailServiceImpl;
import com.wosiliujing.learning.service.SecurityUserDetailServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liujing
 * @date 2019/4/27 18:08
 */
@Configuration
@AllArgsConstructor
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final DataSource dataSource;

    private final AuthenticationManager authenticationManager;

    private final RedisConnectionFactory redisConnectionFactory;

    private final SecurityUserDetailServiceImpl myUserDetailService;

    private final SecurityProperties securityProperties;

    @Bean
    public TokenStore tokenStore(){
        RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
        tokenStore.setPrefix(SecurityConstants.TOKEN_PREFIX);
        return tokenStore;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security)  {
        security
                .allowFormAuthenticationForClients()
                .checkTokenAccess("isAuthenticated()");
    }


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        ClientDetailServiceImpl myClientDetailService = new ClientDetailServiceImpl(dataSource);
        myClientDetailService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
        myClientDetailService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
        clients.withClientDetails(myClientDetailService);
    }

    @Bean
    public JdbcClientDetailsService securityClientDetailService(){
        ClientDetailServiceImpl myClientDetailService = new ClientDetailServiceImpl(dataSource);
        myClientDetailService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
        myClientDetailService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
        return myClientDetailService;
    }

    @Bean
    @Primary
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenEnhancer(tokenEnhancer());
        tokenServices.setClientDetailsService(securityClientDetailService());
        tokenServices.setAccessTokenValiditySeconds(securityProperties.getTokenValidTime());
        tokenServices.setRefreshTokenValiditySeconds(securityProperties.getRefreshTokenValidTime());
        return tokenServices;
    }

    /**
     * 配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)
     * @param endpoints
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)  {
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.POST,HttpMethod.GET)
        .tokenStore(tokenStore())
        .tokenEnhancer(tokenEnhancer())
        .userDetailsService(myUserDetailService)
        .authenticationManager(authenticationManager)
        .reuseRefreshTokens(false)
                .tokenServices(tokenServices())
                .pathMapping("/oauth/confirm_access", "/token/confirm_access")
                .exceptionTranslator(new Oauth2WebResponseExceptionTranslator());

    }

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return (accessToken, authentication) -> {
            final Map<String, Object> additionalInfo = new HashMap<>(8);
            if (SecurityConstants.CLIENT_CREDENTIALS
                    .equals(authentication.getOAuth2Request().getGrantType())) {
                return accessToken;
            }

            SecurityUser user = (SecurityUser) authentication.getUserAuthentication().getPrincipal();
            additionalInfo.put(SecurityConstants.ENHANCE_MAP,user.getEnhanceMap());
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            return accessToken;
        };
    }
}
